package chapter_1.demo_1;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: hero生仔
 */
public class Apple {
    Integer weight;
    String color;

    public static boolean isGreenApple(Apple apple) {
        return "green".equals(apple.color);
    }

    public static boolean isHeavyApple(Apple apple) {
        return apple.weight > 150;
    }

    public interface  Predicate<T> {
        boolean test(T t);
    }

    static List<Apple> filterApples(List<Apple> inventory,Predicate<Apple> p) {
        ArrayList<Apple> result = new ArrayList<>();
        for (Apple apple : inventory) {
            if (p.test(apple)) {
                result.add(apple);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        // 假如我现在有两个要求,筛选出绿色的苹果 或者 筛选出超过150g的苹果,为了避免重复的代码出现,我们可以使用上述的代码结构.
        Apple.filterApples(new ArrayList<>(),Apple::isHeavyApple);
//        Apple.filterApples(new ArrayList<>(),(apple) -> isHeavyApple(apple)); // 可以有这种写法
//        Apple.filterApples(new ArrayList<>(),(apple) -> { // 也可以有这种写法
//            return isHeavyApple(apple);
//        });
        Apple.filterApples(new ArrayList<>(),Apple::isGreenApple);
    }
}
